<?php

namespace App\Services;
use App\Exceptions\SysExceptions;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use GuzzleHttp\Exception\GuzzleException;

class PayServices
{
    private static $config = [
        // 必要配置
        'app_id'             => 'wxbaf553129f46f40e',
        'mch_id'             => '1668389019',
        'key'                => 'c5e467d8b9aefb0d0c6bfb8ad1fec419',   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)

        // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
        'cert_path'          => '', // XXX: 绝对路径！！！！
        'key_path'           => '',
    ];

    /**
     * @throws InvalidArgumentException
     * @throws InvalidConfigException
     * @throws GuzzleException|SysExceptions
     */
    public static function pay($params = []): array
    {
        $params['price'] = 0.01;
        $app = Factory::payment(array_merge(self::$config,[
            'notify_url'=>$params['notify_url']
        ]));
        $result = $app->order->unify([
            'body' => '面膜',
            'out_trade_no' => $params['order_code'],
            'total_fee' => floor($params['price']*100),
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $params['openid'],
        ]);


        if ($result['return_code'] === 'SUCCESS') {
            $jssdk = $app->jssdk;
            $prepayId = $result['prepay_id'];
            $config = $jssdk->sdkConfig($prepayId);
            return  $config;
        }
        throw new SysExceptions('支付失败');
    }


    public static function get_app(): \EasyWeChat\Payment\Application
    {
        return Factory::payment(self::$config);
    }
}
